/*
 * SvcRepairHandler.java
 *
 * Created on March 29, 2007, 11:00 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.group1E;

import edu.byu.isys413.group1E.data.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 *
 * @author tkulbeth
 */
public class SvcRepairHandler {
    
    /**
     * Contains an instance of SvcRepairHandler
     */
    private static SvcRepairHandler instance = null;
    
    /**
     * Creates a new instance of SvcRepairHandler
     */
    public SvcRepairHandler() {
    }
    
    /**
     * Retrieves an instance of the SvcRepairHandler object
     *
     * @return instance of SvcRepairHandler
     */
    public static synchronized SvcRepairHandler getInstance() {
        if (instance == null) {
            instance = new SvcRepairHandler();
        }
        return instance;
    }
    
    /** This method is created when an item is brought in to be repaired. It requires that the employee
     *enter an estimate for the labor hours required for the repair, as well as the preferred contact method
     *as stated by the employee upon bringing in the broken item.
     *
     *@param transDate is only passed in when the customer brings in a conceptual product that they know
     *of the date when they purchased it, or the employee has looked it up.  Otherwise the employee will
     * search for the transaction and get the date visually before creating this service repair.
     */
    public synchronized SvcRepairBO newSvcRepair(String prod_xid, String transDate,
        String custID, String contactMethod, String labor, String price, String employeeID) throws Exception{
        SvcRepairBO sr = (SvcRepairBO)SvcRepairDAO.getInstance().create();
        char first = prod_xid.charAt(0);
        if(first == 'P'){
            sr.setProduct((ForSaleBO)ForSaleDAO.getInstance().readBySKU(prod_xid));
//            System.out.println("SR product: " + sr.getProduct().getProductID());
            sr.setTransDate(this.getTransactionDate(sr.getProduct(), custID));
//            System.out.println("Trans date: " + sr.getTransDate());
            ForSaleBO prod = (ForSaleBO)sr.getProduct();
            if(prod.getNewUsed()){      //if product was purchased new, check the warranty
                sr.setCoveredByWarranty(this.checkWarranty(prod.getConceptual().getWarranty(), sr));
            }else{  //if the product was purchased used, it cannot be covered by the warranty
                sr.setCoveredByWarranty(false);
            }
        }else{
            sr.setProduct((ConceptualBO)ConceptualDAO.getInstance().readBySKU(prod_xid));
            sr.setTransDate(transDate);
            ConceptualBO prod = (ConceptualBO)sr.getProduct();
            sr.setCoveredByWarranty(this.checkWarranty(prod.getWarranty(), sr));
        }
        Calendar cal = Calendar.getInstance();
        Date today = cal.getTime();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = fmt.format(today);
        sr.setProductID(sr.getProduct().getProductID());
        sr.setDescription("Repair of product: " + sr.getProductID());
        sr.setStartDate(todayDate);
        sr.setContactMethod(contactMethod);
        sr.setLaborHrs(Double.parseDouble(labor));
        sr.setPrice(Double.parseDouble(price));
        sr.setEmployeeID(employeeID);
        sr.setType("repair");
        return sr;
    }
    
    
    /**
     *@param sr contains the service repair object being created
     *@param x indicates whether the product is physical or conceptual
     */
    public String getTransactionDate(ProductBO prod, String custID) throws Exception{
        ArrayList<RevenueSourceBO> sales = SaleDAO.getInstance().readByProductID(prod.getProductID());
        String date = null;
        //get the first element of the array, since the request was for a physical product
        if(sales.isEmpty() == false){
            SaleBO sale = (SaleBO)sales.get(0);
            TransLineBO txLine = TransLineDAO.getInstance().readByRevSrc(sale.getRevSrcID());
//            System.out.println("Sale id: " +  sale.getRevSrcID());
            date = TransactionDAO.getInstance().read(txLine.getTransactionID()).getTransDate();
        }
        return date;
    }
    
    /**
     *
     */
    public boolean checkWarranty(WarrantyBO war, SvcRepairBO sr){
        //get the current date
        Calendar cal = Calendar.getInstance();
        Date today = cal.getTime();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = fmt.format(today);
        java.sql.Date dt1 = java.sql.Date.valueOf(todayDate);
        //get the warranty month
        int months = war.getWLength();
        //get the warranty expiration date
        java.sql.Date warEndDate = this.getWarEndDate(sr.getTransDate(), months);
        //check if the warranty is still valid
        if(dt1.before(warEndDate)){ return true;} else{ return false; }
    }
    
    /**
     *
     */
    public java.sql.Date getWarEndDate(String transDate, int months){
//        System.out.println(transDate.substring(8,10));
        int transDay = Integer.parseInt(transDate.substring(8,10));
        int transYear = Integer.parseInt(transDate.substring(0,4));
        int addYears = months / 12;
//        System.out.println("months: " + months);
//        System.out.println("add years: " + addYears);
        int expYear = transYear + addYears;
        int transMonth = Integer.parseInt(transDate.substring(5,7));
        int expMonth = transMonth + (months - (addYears * 12));
        //check if the new month exceeds the length of a year
        if(expMonth > 12){
            expYear += 1;
            expMonth -= 12;
        }
        String expDate = "";
        expDate = expDate.concat(Integer.toString(expYear).concat("-").concat(Integer.toString(expMonth)).concat("-").concat(Integer.toString(transDay)));
//        System.out.println("ExpDate: " + expDate);
        return java.sql.Date.valueOf(expDate);
    }
    
    /** This method updates the remaining fields in the SvcRepairBO
     *@param sr contains the SvcRepairBO to be updated, which is passed in every time
     *@param compDate contains the completion date, could be null
     *@param pickupDate contains the date the customer picked up the repaired item
     *@param lastNotice contains the date the customer was last notified
     *@return the updated SvcRepairBO
     */
    public synchronized SvcRepairBO updateSvcRepair(SvcRepairBO sr, String compDate, String pickupDate, String lastNotice, String newPrice, String hrs) throws Exception{
        if(sr.getCompleteDate() == null){ //if this hasn't been set yet
            sr.setCompleteDate(compDate);
        }
        if(sr.getPickUpDate() == null){ //if this hasn't been set yet
            sr.setPickUpDate(pickupDate);
        }
        if(lastNotice != null){ //update the lastNoticeDate if it's changing
            sr.setLastNoticeDate(lastNotice);
        }
        if(newPrice != null){
            sr.setPrice(Double.parseDouble(newPrice));
        }
        if(hrs != null){
            sr.setLaborHrs(Double.parseDouble(hrs));
        }
        return sr;
    }
    
}
